package com.xique.blelock.view.AcountManager;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.MD5Util;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.VCodeType;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.view.Thtreepackage.CountDownButtonHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ForgetPassword_activity extends BaseActivity implements View.OnClickListener {
    private static final String TAG ="ForgetPassword_activity" ;
    /**
     * 忘记密码登录需重新设置
     *
     * @param savedInstanceState
     */
    private Button WANcehng;
    private TextView Mbtnsend;
    private EditText iphones,yanzcode,passward;

    private boolean falgse = false;
    private boolean falgs1 = false;

    @BindView(R.id.passwdmode)
    ToggleButton passwdmode;

    @BindView(R.id.title)
    TextView title;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forgetpassord);
        ButterKnife.bind(this);
        initview();//初始化界面
    }

    private void initview() {
        iphones = findViewById(R.id.iphoines);
        yanzcode = findViewById(R.id.yanzhnema);
        passward = findViewById(R.id.passwards);
//        QRPasswar = findViewById(R.id.passwardes);
        Mbtnsend = findViewById(R.id.sendyanmma);
        WANcehng = findViewById(R.id.wancheng);
//        backlogin = findViewById(R.id.backlogin);
//        xianshimima1 = findViewById(R.id.xianshimima1);
//        xianshimima = findViewById(R.id.xianshimima);
        Mbtnsend.setOnClickListener(this);
//        xianshimima.setOnClickListener(this);
//        xianshimima1.setOnClickListener(this);
//      backlogin.setOnClickListener(this);
        WANcehng.setOnClickListener(this);
        WANcehng.setEnabled(false);

        title.setText("忘记密码");

        iphones.addTextChangedListener(textWatcher);
        yanzcode.addTextChangedListener(textWatcher);
        passward.addTextChangedListener(textWatcher);
    }

    //切换密码模式
    @OnClick(R.id.passwdmode)
    public void SwitchPwdmod() {
        if(passwdmode.isChecked()){
            //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
            passward.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }else{
            //选择状态 显示明文--设置为可见的密码
            passward.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sendyanmma:
                String phones = iphones.getText().toString();//获取号码
                Pattern p = Pattern.compile("[0-9]*");
                Matcher m = p.matcher(phones);
                if (m.matches()) {
                    if (phones.length() >= 11) {
                        Getvcode();
                        }else {
                            Toast.makeText(this, "输入手机号有误", Toast.LENGTH_SHORT).show();
                        }
                }

                break;

            case R.id.wancheng:
                ReSetpasswd();
                break;

        }
    }

    @OnClick(R.id.BACKER)
    public void BackLastPage(){
        finish();
    }

    private void ReSetpasswd() {
        String phones = iphones.getText().toString();//获取号码
        String getvcode = yanzcode.getText().toString();//获取验证码
        String passwared = passward.getText().toString();//获取密码
           {
           XqNetClient netClient = new XqNetClient();
           JSONObject jsonobject = new JSONObject();
           try {
               jsonobject.put("phone", phones);
               jsonobject.put("password", MD5Util.md5(passwared));
               jsonobject.put("vCode", getvcode);
               jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
           } catch (JSONException e) {
               e.printStackTrace();
           }
           netClient.ReSetpasswd(jsonobject.toString()).enqueue(new Callback<String>() {
               @Override
               public void onResponse(Call<String> call, Response<String> response) {
                   System.out.println("-===获取的验证码是：" + response.body());
                   Log.e(TAG, "-===获取设置密码信息：" + response.body());
                   String code = "1";
                   try {
                       JSONObject jsonObject = new JSONObject(response.body());
                       code = jsonObject.getString("message");
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
                   if (code.equals("成功")) {//如果成功就跳转到主界面
                       Toast.makeText(ForgetPassword_activity.this,"密码设置成功",Toast.LENGTH_SHORT).show();
                       finish();
                   }else{
                       showToast(ForgetPassword_activity.this, "密码重置失败："+code);
                   }
               }

               @Override
               public void onFailure(Call<String> call, Throwable t) {
                   t.printStackTrace();
               }
           });
       }
    }

    /**
     * 获取验证码
     */
    private void  Getvcode() {
        String phones = iphones.getText().toString();//获取号码
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("phone", phones);
            jsonobject.put("mode", VCodeType.ModifyPwd);
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        netClient.sendAuthCode(jsonobject.toString()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                System.out.println("-===获取的验证码是："+ response.body());
                Log.e(TAG, "-===获取的验证码是：" + response.body());
                String code = "1";
                try {
                    JSONObject jsonObject1 = new JSONObject(response.body());
                    code = jsonObject1.getString("message");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (code.equals("成功")) {//如果成功就跳转到主界面
                    showToast(ForgetPassword_activity.this,"密码已经发送请注意查收");
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
            }
        });
        CountDownButtonHelper helper = new CountDownButtonHelper(Mbtnsend,
                "发送验证码", 60, 1);
        helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() {

            @Override
            public void finish() {
                Mbtnsend.setText("重新发送");
            }
        });
        helper.start();
    }

    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if(iphones.getText().length()>= 6 && (yanzcode.getText().length() >=6)
                    && (passward.getText().length()>=6)){
                WANcehng.setEnabled(true);
            }else{
                WANcehng.setEnabled(false);
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void afterTextChanged(Editable s) {  }
    };
}
